<template>
  <div class="dashboard-overview">
    <h1 class="page-title">业务总览</h1>

    <!-- 关键指标卡片组 -->
    <div class="kpi-cards">
      <el-row :gutter="20">
        <el-col :span="6" v-for="(card, index) in kpiCards" :key="index">
          <el-card class="kpi-card" :class="card.type">
            <div class="card-icon">
              <el-icon>
                <component :is="card.icon" />
              </el-icon>
            </div>
            <div class="card-content">
              <div class="card-title">{{ card.title }}</div>
              <div class="card-value">{{ card.format(animatedValues[index]) }}</div>
              <div class="card-change" :class="card.trend">
                <el-icon>
                  <component :is="card.trend === 'up' ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
                {{ card.change }}
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 图表区域 -->
    <div class="chart-container">
      <el-row :gutter="20">
        <!-- 销售趋势图 -->
        <el-col :span="16">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <h3>销售趋势</h3>
                <div class="chart-controls">
                  <el-radio-group v-model="salesTimeRange" size="small">
                    <el-radio-button label="week">周</el-radio-button>
                    <el-radio-button label="month">月</el-radio-button>
                    <el-radio-button label="year">年</el-radio-button>
                  </el-radio-group>
                </div>
              </div>
            </template>
            <div class="chart" id="sales-trend-chart"></div>
          </el-card>
        </el-col>

        <!-- 订单来源分析 -->
        <el-col :span="8">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <h3>订单来源分析</h3>
              </div>
            </template>
            <div class="chart" id="order-source-chart"></div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px;">
        <!-- 产品销量排行 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <h3>产品销量排行</h3>
                <div class="chart-controls">
                  <el-select v-model="productRankCategory" size="small" placeholder="选择类别">
                    <el-option v-for="item in categories" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </div>
              </div>
            </template>
            <div class="chart" id="product-rank-chart"></div>
          </el-card>
        </el-col>

        <!-- 地区销售分布 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <h3>地区销售分布</h3>
              </div>
            </template>
            <div class="chart" id="region-sales-chart"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import * as echarts from 'echarts'
import { Money, ShoppingBag, Goods, Van } from '@element-plus/icons-vue'

// KPI卡片数据
const kpiCards = [
  {
    title: '总销售额',
    value: '￥2,345,678',
    numericValue: 2345678,
    format: (val: number) => `￥${val.toLocaleString()}`,
    change: '12.5%',
    trend: 'up',
    icon: 'Money',
    type: 'sales'
  },
  {
    title: '订单数',
    value: '1,234',
    numericValue: 1234,
    format: (val: number) => val.toLocaleString(),
    change: '8.2%',
    trend: 'up',
    icon: 'ShoppingBag',
    type: 'orders'
  },
  {
    title: '库存量',
    value: '5,678',
    numericValue: 5678,
    format: (val: number) => val.toLocaleString(),
    change: '3.1%',
    trend: 'down',
    icon: 'Goods',
    type: 'inventory'
  },
  {
    title: '发货量',
    value: '987',
    numericValue: 987,
    format: (val: number) => val.toLocaleString(),
    change: '5.6%',
    trend: 'up',
    icon: 'Van',
    type: 'delivery'
  }
]

// 动画显示的值
const animatedValues = ref(kpiCards.map(() => 0))

// 动画效果函数
const animateValues = () => {
  // 为每个卡片创建动画
  kpiCards.forEach((card, index) => {
    const targetValue = card.numericValue
    const duration = 2000 // 动画持续2秒
    const startTime = Date.now()
    
    const animate = () => {
      const currentTime = Date.now()
      const elapsed = currentTime - startTime
      
      if (elapsed < duration) {
        // 使用easeOutExpo缓动函数让动画更自然
        const progress = 1 - Math.pow(1 - elapsed / duration, 3)
        animatedValues.value[index] = Math.floor(targetValue * progress)
        requestAnimationFrame(animate)
      } else {
        animatedValues.value[index] = targetValue
      }
    }
    
    animate()
  })
}

// 图表控制变量
const salesTimeRange = ref('month')
const productRankCategory = ref('all')
const categories = [
  { label: '所有类别', value: 'all' },
  { label: '电子产品', value: 'electronics' },
  { label: '服装', value: 'clothing' },
  { label: '食品', value: 'food' },
  { label: '家居', value: 'home' }
]

// 图表实例
let salesChart: echarts.ECharts | null = null
let orderSourceChart: echarts.ECharts | null = null
let productRankChart: echarts.ECharts | null = null
let regionSalesChart: echarts.ECharts | null = null

// 初始化销售趋势图
const initSalesChart = () => {
  if (!salesChart) {
    salesChart = echarts.init(document.getElementById('sales-trend-chart') as HTMLElement)
  }

  // 根据选择的时间范围获取数据
  const { xData, yData } = getSalesData(salesTimeRange.value)

  const option = {
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: xData
    },
    yAxis: {
      type: 'value',
      name: '销售额 (万元)'
    },
    series: [
      {
        name: '销售额',
        type: 'line',
        smooth: true,
        lineStyle: {
          width: 3,
          color: '#409EFF'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
              { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
            ]
          }
        },
        data: yData
      }
    ]
  }

  salesChart.setOption(option)
}

// 根据选择的时间范围获取销售数据
const getSalesData = (timeRange: string) => {
  let xData: string[] = []
  let yData: number[] = []

  // 模拟数据
  switch (timeRange) {
    case 'week':
      xData = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
      yData = [120, 132, 101, 134, 90, 230, 210]
      break
    case 'month':
      xData = Array.from({ length: 30 }, (_, i) => `${i + 1}日`)
      yData = Array.from({ length: 30 }, () => Math.floor(Math.random() * 300 + 50))
      break
    case 'year':
      xData = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
      yData = [320, 332, 301, 334, 390, 330, 320, 310, 301, 302, 330, 350]
      break
  }

  return { xData, yData }
}

// 初始化订单来源分析图
const initOrderSourceChart = () => {
  if (!orderSourceChart) {
    orderSourceChart = echarts.init(document.getElementById('order-source-chart') as HTMLElement)
  }

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: ['线上商城', '线下门店', '第三方平台', '电话订单', '其他']
    },
    series: [
      {
        name: '订单来源',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        data: [
          { value: 335, name: '线上商城' },
          { value: 310, name: '线下门店' },
          { value: 234, name: '第三方平台' },
          { value: 135, name: '电话订单' },
          { value: 48, name: '其他' }
        ]
      }
    ]
  }

  orderSourceChart.setOption(option)
}

// 初始化产品销量排行图
const initProductRankChart = () => {
  if (!productRankChart) {
    productRankChart = echarts.init(document.getElementById('product-rank-chart') as HTMLElement)
  }

  // 根据选择的类别获取数据
  const { products, sales } = getProductRankData(productRankCategory.value)

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      name: '销量'
    },
    yAxis: {
      type: 'category',
      data: products,
      axisLabel: {
        formatter: (value: string) => {
          if (value.length > 10) {
            return value.substring(0, 10) + '...'
          }
          return value
        }
      }
    },
    series: [
      {
        name: '销量',
        type: 'bar',
        data: sales
      }
    ]
  }

  productRankChart.setOption(option)
}

// 根据选择的类别获取产品销量排行数据
const getProductRankData = (category: string) => {
  // 模拟数据
  let products: string[] = []
  let sales: number[] = []

  switch (category) {
    case 'electronics':
      products = ['智能手机', '笔记本电脑', '平板电脑', '智能手表', '无线耳机', '智能音箱', '相机']
      sales = [1200, 980, 750, 620, 580, 450, 320]
      break
    case 'clothing':
      products = ['T恤', '牛仔裤', '运动鞋', '休闲外套', '连衣裙', '衬衫', '羽绒服']
      sales = [850, 720, 680, 590, 540, 480, 420]
      break
    case 'food':
      products = ['进口零食', '坚果炒货', '乳制品', '休闲食品', '饮料', '酒水', '茶叶']
      sales = [960, 890, 780, 720, 670, 610, 520]
      break
    case 'home':
      products = ['床上用品', '厨房用具', '智能家居', '收纳用品', '家居装饰', '清洁用品', '卫浴用品']
      sales = [680, 650, 620, 580, 550, 510, 480]
      break
    default:
      products = ['智能手机', '进口零食', 'T恤', '笔记本电脑', '床上用品', '牛仔裤', '坚果炒货', '休闲外套']
      sales = [1200, 960, 850, 820, 780, 720, 690, 650]
  }

  return { products, sales }
}

// 初始化地区销售分布图
const initRegionSalesChart = () => {
  if (!regionSalesChart) {
    regionSalesChart = echarts.init(document.getElementById('region-sales-chart') as HTMLElement)
  }

  // 准备数据
  const data = [
    { name: '华东', value: 1200 },
    { name: '华北', value: 900 },
    { name: '华南', value: 800 },
    { name: '华中', value: 700 },
    { name: '西南', value: 600 },
    { name: '西北', value: 500 },
    { name: '东北', value: 400 }
  ]

  // 计算数据最大值
  const max = Math.max(...data.map(item => item.value))

  const option = {
    tooltip: {
      trigger: 'item'
    },
    visualMap: {
      show: false,
      min: 0,
      max: max,
      inRange: {
        color: ['#e0f5ff', '#409EFF']
      }
    },
    series: [
      {
        type: 'map',
        map: 'china',
        zoom: 1.2,
        label: {
          show: true,
          fontSize: 10
        },
        emphasis: {
          label: {
            color: '#fff'
          },
          itemStyle: {
            areaColor: '#67C23A'
          }
        },
        data
      }
    ]
  }

  regionSalesChart.setOption(option)
}

// 监听时间范围变化
watch(salesTimeRange, () => {
  initSalesChart()
})

// 监听产品类别变化
watch(productRankCategory, () => {
  initProductRankChart()
})

// 自适应图表大小
const handleResize = () => {
  salesChart?.resize()
  orderSourceChart?.resize()
  productRankChart?.resize()
  regionSalesChart?.resize()
}

// 在组件挂载后初始化图表
onMounted(() => {
  // 动态加载中国地图数据
  echarts.registerMap('china', {
    type: 'FeatureCollection',
    features: []
  })

  // 初始化所有图表
  initSalesChart()
  initOrderSourceChart()
  initProductRankChart()
  initRegionSalesChart()

  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize)
  
  // 启动数值动画
  animateValues()
})

// 在组件卸载前销毁图表实例
onBeforeUnmount(() => {
  if (salesChart) {
    salesChart.dispose()
    salesChart = null
  }
  if (orderSourceChart) {
    orderSourceChart.dispose()
    orderSourceChart = null
  }
  if (productRankChart) {
    productRankChart.dispose()
    productRankChart = null
  }
  if (regionSalesChart) {
    regionSalesChart.dispose()
    regionSalesChart = null
  }

  // 移除窗口大小变化监听
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.dashboard-overview {
  padding: 20px;
}

.page-title {
  font-size: 24px;
  margin-bottom: 20px;
  color: #303133;
}

/* KPI卡片样式 */
.kpi-cards {
  margin-bottom: 20px;
}

.kpi-card {
  height: 120px;
  display: flex;
  align-items: center;
  overflow: hidden;
  position: relative;
}

.kpi-card.sales {
  border-top: 3px solid #409EFF;
}

.kpi-card.orders {
  border-top: 3px solid #67C23A;
}

.kpi-card.inventory {
  border-top: 3px solid #E6A23C;
}

.kpi-card.delivery {
  border-top: 3px solid #F56C6C;
}

.card-icon {
  position: absolute;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 60px;
  opacity: 0.2;
}

.card-content {
  /* padding: 0 20px; */
}

.card-title {
  font-size: 16px;
  color: #909399;
  margin-bottom: 10px;
}

.card-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 10px;
}

.card-change {
  font-size: 14px;
  display: flex;
  align-items: center;
}

.card-change.up {
  color: #67C23A;
}

.card-change.down {
  color: #F56C6C;
}

/* 图表样式 */
.chart-card {
  margin-bottom: 20px;
  height: 400px;
}

.chart {
  width: 100%;
  height: 330px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.chart-controls {
  display: flex;
  align-items: center;
}

@media screen and (max-width: 768px) {
  .kpi-cards .el-col {
    margin-bottom: 15px;
  }
  
  .chart-card {
    height: auto;
    margin-bottom: 15px;
  }
  
  .chart {
    height: 250px;
  }
}
</style> 